import requests
from handler.request_handler import RequestInfo
from constant.info import *


class DoRequest:
    def __init__(self, url, method, params_file_path=None):
        self.url = url
        self.method = method
        self.request_method = {
            'post': self.do_post,
            'get': self.do_get
        }
        self.response = self.run()

    def do_get(self):
        requests_info = RequestInfo(self.url)
        r = requests.get(
            url=requests_info.url,
            params=requests_info.form,
            headers=requests_info.headers,
            cookies=requests_info.cookies
        )
        return r

    def do_post(self):
        requests_info = RequestInfo(self.url)
        r = requests.post(
            url=requests_info.url,
            data=requests_info.form,
            headers=requests_info.headers,
            cookies=requests_info.cookies
        )
        return r

    def run(self):
        r = self.request_method[self.method]()
        if r.status_code != 200:
            raise ConnectionError('请求失败，相应码{code_status} 相应内容:{info}'.format(
                code_status=r.status_code,
                info=r.json()
            ))
        elif r.json()['result'] != 1:
            raise ConnectionError(
                '接口返回失败, result: {}， error_msg: {}'.format(
                    r.json()['result'],
                    r.json()['error_msg']
                )
            )
        return r.json()


if __name__ == '__main__':
    r = DoRequest(api, 'post')
    print(r.run())
